package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.CurrentApp;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OpenAppMapper;
import com.ruoyi.system.domain.OpenApp;
import com.ruoyi.system.service.IOpenAppService;

import javax.annotation.PostConstruct;

/**
 * 申请权限的应用Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-26
 */
@Service
public class OpenAppServiceImpl implements IOpenAppService {
    @Autowired
    private OpenAppMapper openAppMapper;
    @Autowired
    private RedisCache redisCache;


    @PostConstruct
    public void init(){
        List<OpenApp> appList = openAppMapper.selectOpenAppList(null);
        appList.forEach(app->{
            redisCache.setCacheObject(getCacheKey(app.getAppName()), new CurrentApp(app.getAppName(), app.getAppToken(), 0));
        });
    }
    /**
     * 查询申请权限的应用
     *
     * @param id 申请权限的应用主键
     * @return 申请权限的应用
     */
    @Override
    public OpenApp selectOpenAppById(Long id) {
        return openAppMapper.selectOpenAppById(id);
    }

    /**
     * 查询申请权限的应用列表
     *
     * @param openApp 申请权限的应用
     * @return 申请权限的应用
     */
    @Override
    public List<OpenApp> selectOpenAppList(OpenApp openApp) {
        return openAppMapper.selectOpenAppList(openApp);
    }

    /**
     * 新增申请权限的应用
     *
     * @param openApp 申请权限的应用
     * @return 结果
     */
    @Override
    public int insertOpenApp(OpenApp openApp) {
        int i = openAppMapper.insertOpenApp(openApp);
        redisCache.setCacheObject(getCacheKey(openApp.getAppName()), new CurrentApp(openApp.getAppName(), openApp.getAppToken(), 0));
        return i;
    }

    private String getCacheKey(String app) {
        return CacheConstants.LOGIN_TOKEN_KEY + "app:" + app;
    }

    /**
     * 修改申请权限的应用
     *
     * @param openApp 申请权限的应用
     * @return 结果
     */
    @Override
    public int updateOpenApp(OpenApp openApp) {
        int i = openAppMapper.updateOpenApp(openApp);

        redisCache.setCacheObject(getCacheKey(openApp.getAppName()), new CurrentApp(openApp.getAppName(), openApp.getAppToken(), 0));
        return i;
    }

    /**
     * 批量删除申请权限的应用
     *
     * @param ids 需要删除的申请权限的应用主键
     * @return 结果
     */
    @Override
    public int deleteOpenAppByIds(Long[] ids) {
        return openAppMapper.deleteOpenAppByIds(ids);
    }

    /**
     * 删除申请权限的应用信息
     *
     * @param id 申请权限的应用主键
     * @return 结果
     */
    @Override
    public int deleteOpenAppById(Long id) {
        OpenApp openApp = openAppMapper.selectOpenAppById(id);
        int i = openAppMapper.deleteOpenAppById(id);
        if(i>0){
            redisCache.deleteObject(getCacheKey(openApp.getAppName()));
        }
        return i;
    }
}
